package com.example.commons;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 *  基于jackson序列化器实现脱敏操作
 * @author aopmin
 * @since 2025/4/21
 */
// @Component
public final class DataMaskingSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private MaskTypeEnum dataMaskEnum;

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 使用指定的脱敏类型对字符串进行脱敏
        jsonGenerator.writeString(dataMaskEnum.function().apply(s));
    }

    /**
     * 创建序列化器
     * @param prov
     * @param beanProperty
     * @return
     * @throws JsonMappingException
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty beanProperty) throws JsonMappingException {
        // 如果注解不为空，并且字段类型为String类型，则创建序列化器
        DataMask annotation = beanProperty.getAnnotation(DataMask.class);
        if(Objects.nonNull(annotation)&&Objects.equals(String.class,beanProperty.getType().getRawClass())){
            // 获取注解中的脱敏类型
            this.dataMaskEnum=annotation.function();
            return this; // 返回当前序列化器
        }
        return prov.findValueSerializer(beanProperty.getType(),beanProperty); // 否则使用默认序列化器
    }
}